﻿using CSharpWin;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 截图找字体.Properties;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace 截图找字体
{
    public partial class Form1 : Form
    {
        HotKeys h = new HotKeys();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = Settings.Default.快捷键;
            comboBox1.Text = Settings.Default.网站;
            ComboBox1_SelectedIndexChanged(null, null);
            if (textBox1.Text != "")
            {
                Regist(textBox1.Text);
            }
        }
        public delegate void 请求代理(string fileName);
        请求代理 m_请求代理 = 求字体;
        const String 求字体_URL = "http://www.qiuziti.com/s/upload.ashx";
        static void 求字体(string fileName)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(求字体_URL);
            webReq.Method = "POST";
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            webReq.KeepAlive = true;
            webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            webReq.Headers.Add("Origin", "http://www.qiuziti.com");
            webReq.Referer = "http://www.qiuziti.com";

            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
            string formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            string dataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            var formdata = string.Format(formdataTemplate, "uploaded_file", Path.GetFileName(fileName));

            webReq.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //文件头
            var formdataByte = Encoding.ASCII.GetBytes(formdata);
            //尾
            var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            Stream requestStream = webReq.GetRequestStream();
            requestStream.Write(formdataByte, 0, formdataByte.Length);//写入 文件头
            var streamByte = File.ReadAllBytes(fileName);
            requestStream.Write(streamByte, 0, streamByte.Length);//写入 文件

            //var dataByte1 = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "textfield", ""));
            //requestStream.Write(dataByte1, 0, dataByte1.Length);//写入 参数1


            requestStream.Write(footer, 0, footer.Length);//写入 尾

            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                if (response.ResponseUri != null)
                {
                    var rUrl = response.ResponseUri.AbsoluteUri;
                    if (rUrl.IndexOf("Confirm.aspx") > -1)
                    {
                        System.Diagnostics.Process.Start(response.ResponseUri.AbsoluteUri);
                    }
                    else
                    {
                        MessageBox.Show("错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            response.Close();
        }
        #region 求字体_新

        public struct 求字体_新_结果
        {
            public string path { get; set; }
            public bool success { get; set; }
            public int errorCode { get; set; }
            public string url { get; set; }
        }
        const String 求字体_新_URL = "http://new.qiuziti.com/font/uploadFontImg";
        static void 求字体_新(string fileName)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(求字体_新_URL);
            webReq.Method = "POST";
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            webReq.KeepAlive = true;
            webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            webReq.Headers.Add("Origin", "http://new.qiuziti.com/");
            webReq.Referer = "http://new.qiuziti.com/";

            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
            string formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            string dataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            var formdata = string.Format(formdataTemplate, "file", Path.GetFileName(fileName));

            webReq.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //文件头
            var formdataByte = Encoding.ASCII.GetBytes(formdata);
            //尾
            var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            Stream requestStream = webReq.GetRequestStream();
            requestStream.Write(formdataByte, 0, formdataByte.Length);//写入 文件头
            var streamByte = File.ReadAllBytes(fileName);
            requestStream.Write(streamByte, 0, streamByte.Length);//写入 文件

            //var dataByte1 = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "textfield", ""));
            //requestStream.Write(dataByte1, 0, dataByte1.Length);//写入 参数1


            requestStream.Write(footer, 0, footer.Length);//写入 尾

            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var rs = response.GetResponseStream();
                byte[] bb = new byte[response.ContentLength];
                rs.Read(bb, 0, bb.Length);
                var sss = Encoding.UTF8.GetString(bb);
                var result = JsonConvert.DeserializeObject<求字体_新_结果>(sss);
                if (result.success)
                {
                    var targetUrl = $"http://new.qiuziti.com/confirm.html?path={Uri.EscapeDataString(result.path)}&a=t";
                    System.Diagnostics.Process.Start(targetUrl);
                }
                else
                {
                    MessageBox.Show($"错误,代码:{result.errorCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                rs.Close();
            }
            response.Close();
        }
        #endregion
        #region 求字体_新

        public struct 求字体_新_结果1
        {
            public string path { get; set; }
            public bool success { get; set; }
            public int errorCode { get; set; }
            public string url { get; set; }
        }
        const String 识字体_URL = "https://www.likefont.com/identify/start";
        static void 识字体(string fileName)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(识字体_URL);
            webReq.Method = "POST";
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            webReq.Accept = "*/*";
            webReq.KeepAlive = true;
            webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            webReq.Headers.Add("Origin", "https://www.likefont.com/");
            webReq.Referer = "https://www.likefont.com/";

            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
            string formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/png\r\n\r\n";
            string dataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            var formdata = string.Format(formdataTemplate, "file", Path.GetFileName(fileName));

            webReq.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //文件头
            var formdataByte = Encoding.ASCII.GetBytes(formdata);
            //尾
            var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            Stream requestStream = webReq.GetRequestStream();

            var streamByte = File.ReadAllBytes(fileName);

            var dataByte = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "id", "WU_FILE_0"));
            requestStream.Write(dataByte, 0, dataByte.Length);//写入 参数1
            dataByte = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "name", Path.GetFileName(fileName)));
            requestStream.Write(dataByte, 0, dataByte.Length);//写入 参数1
            dataByte = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "type", "image/png"));
            requestStream.Write(dataByte, 0, dataByte.Length);//写入 参数1
            dataByte = Encoding.ASCII.GetBytes(string.Format(dataTemplate, "size", streamByte.Length.ToString()));
            requestStream.Write(dataByte, 0, dataByte.Length);//写入 参数1

            requestStream.Write(formdataByte, 0, formdataByte.Length);//写入 文件头
            requestStream.Write(streamByte, 0, streamByte.Length);//写入 文件


            requestStream.Write(footer, 0, footer.Length);//写入 尾

            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var rs = response.GetResponseStream();
                byte[] bb = new byte[response.ContentLength];
                rs.Read(bb, 0, bb.Length);
                var sss = Encoding.UTF8.GetString(bb);
                var result = JsonConvert.DeserializeObject<求字体_新_结果>(sss);
                if (result.success)
                {
                    var targetUrl = $"http://new.qiuziti.com/confirm.html?path={Uri.EscapeDataString(result.path)}&a=t";
                    System.Diagnostics.Process.Start(targetUrl);
                }
                else
                {
                    MessageBox.Show($"错误,代码:{result.errorCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                rs.Close();
            }
            response.Close();
        }
        #endregion
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.确定关闭 = true;
            this.Close();
        }

        private void 截图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cit = new CaptureImageTool();
            if (cit.ShowDialog() == DialogResult.OK)
            {
                var img = cit.Image;
                var fn = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".png");
                img.Save(fn, ImageFormat.Png);
                m_请求代理(fn);
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        readonly string[] supportType = { ".jpg",".png",".bmp" };
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var fs = (string[]) e.Data.GetData(DataFormats.FileDrop);
                var fileName = fs[0];
                var ext = Path.GetExtension(fileName);
                if (Array.IndexOf(supportType,ext) > -1)
                {
                    m_请求代理(fileName);
                }
                else
                {
                    MessageBox.Show($"不支持的格式{ext}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void TextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            StringBuilder keyValue = new StringBuilder();
            keyValue.Length = 0;
            keyValue.Append("");
            if (e.Modifiers != 0)
            {
                if (e.Control)
                    keyValue.Append("Ctrl + ");
                if (e.Alt)
                    keyValue.Append("Alt + ");
                if (e.Shift)
                    keyValue.Append("Shift + ");
            }
            if ((e.KeyValue >= 33 && e.KeyValue <= 40) ||
                (e.KeyValue >= 65 && e.KeyValue <= 90) ||   //a-z/A-Z
                (e.KeyValue >= 112 && e.KeyValue <= 123))   //F1-F12
            {
                keyValue.Append(e.KeyCode);
            }
            else if ((e.KeyValue >= 48 && e.KeyValue <= 57))    //0-9
            {
                keyValue.Append(e.KeyCode.ToString().Substring(1));
            }
            this.textBox1.Text = "";
            //设置当前活动控件的文本内容
            this.textBox1.Text = keyValue.ToString();
        }

        private void TextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string str = this.textBox1.Text.TrimEnd();
            int len = str.Length;
            if (len >= 1 && str.Substring(str.Length - 1) == "+")
            {
                this.textBox1.Text = "";
            }
        }
        //按下快捷键时被调用的方法
        public void CallBack()
        {
            截图ToolStripMenuItem_Click(null, null);
        }
        protected override void WndProc(ref Message m)
        {
            //窗口消息处理函数
            h.ProcessHotKey(m);
            base.WndProc(ref m);
        }
        private void Regist(string str)
        {
            if (str == "")
                return;
            int modifiers = 0;
            Keys vk = Keys.None;
            foreach (string value in str.Split('+'))
            {
                if (value.Trim() == "Ctrl")
                    modifiers = modifiers + (int)HotKeys.HotkeyModifiers.Control;
                else if (value.Trim() == "Alt")
                    modifiers = modifiers + (int)HotKeys.HotkeyModifiers.Alt;
                else if (value.Trim() == "Shift")
                    modifiers = modifiers + (int)HotKeys.HotkeyModifiers.Shift;
                else
                {
                    if (Regex.IsMatch(value, @"[0-9]"))
                    {
                        vk = (Keys)Enum.Parse(typeof(Keys), "D" + value.Trim());
                    }
                    else
                    {
                        vk = (Keys)Enum.Parse(typeof(Keys), value.Trim());
                    }
                }
            }
            h.Regist(this.Handle, modifiers, vk, CallBack);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Settings.Default.快捷键 = textBox1.Text;
            Settings.Default.Save();
            h.UnRegist(this.Handle, CallBack);
        }

        private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        bool 确定关闭 = false;
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !确定关闭;
            if (e.Cancel)
            {
                this.Hide();
            }
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox1.Text)
            {
                case "求字体":
                    m_请求代理 = 求字体;
                    break;
                case "求字体_新":
                    m_请求代理 = 求字体_新;
                    break;
                case "识字体":
                    m_请求代理 = 识字体;
                    break;
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            h.UnRegist(this.Handle, CallBack);
            Regist(textBox1.Text);
        }
    }
}
